import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;


public class CreateTextFile {

    private Formatter output; // object used to output text to file
    
    // enable uresr to open teh file
    public void openFile() 
    {
	try 
	{
	    output = new Formatter("clients.txt");
	}
	catch( SecurityException securityEception)
	{
	    System.err.println(
		    "You dont have write access to the file"
		    );
	    System.exit(1);
	}
	catch( FileNotFoundException fileNotFoundException)
	{
	    System.err.println("Error openinig or cerating the file");
	    System.exit(1);
	}
    }
    
    // add records to the file
    public void addRecords()
    {
	AccountRecord record = new AccountRecord();
	Scanner input = new Scanner(System.in);
	
	System.out.printf("%s\n%s\n%s\n%s\n\n",
		"To terminate input, type the end-of-file indicator",
		"when you are prompted to enter input",
		"on unix type <ctrl> d then press enter",
		"on windows type <ctrl> z then press enter"
		);
	System.out.printf("%s\n%s", "Enter account number, first name," +
			"last name and balance","? ");
	
	while(input.hasNext())
	{
	    try // output values to file
	    {
		record.setAccount(input.nextInt());
		record.setFirstName(input.next());
		record.setLastName(input.next());
		record.setBalance(input.nextDouble());
		
		if(record.getAccount() > 0)
		{
		    // write new record
		    output.format("%d %s %s %.2f \n",
			    record.getAccount(),
			    record.getFirstName(),
			    record.getLastName(),
			    record.getBalance()
			    );
		}
		else 
		{
		    System.out.println("Account number must be grather than 0");
		}
	    }
	    catch(FormatterClosedException formatterClosedException)
	    {
		System.err.println("Error writing to file");
		return;
	    }
	    catch(NoSuchElementException elementException)
	    {
		System.err.println("Invalid Input please try again");
		input.nextLine();
	    }
	    
	    System.out.printf("%s\n%s", "Enter account number, first name," +
			"last name and balance","? ");
	}
    }
    
    public void closeFile()
    {
	if(output != null) {
	    output.close();
	}
    }
}
